<template>
    <div class="page-container">
        <!--工具栏-->
        <TableHead
            :config="tableHeaderConfig"
            :searchdata.sync="filters"
            @parentPageList="findTreeList()"
            :tabinline="true"
            v-show="showSearch"
        >
            <template slot="appId">
                <el-select v-model="filters.appId" placeholder="精确查询" size="mini" clearable>
                    <el-option
                        v-for="item in appManagerList"
                        :key="item.appId"
                        :label="item.appName"
                        :value="item.id"
                    />
                </el-select>
            </template>
        </TableHead>
        <!--表格树内容栏-->
        <el-card class="card-box">
            <TableToolBar :showSearch.sync="showSearch" @queryTable="findTreeList" :columns="tableTeeConfig">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd('add')">新增菜单</el-button>
                <el-button type="success" icon="el-icon-caret-bottom" size="mini" @click="expandedRowsChange(true)">
                    展开
                </el-button>
                <el-button type="danger" icon="el-icon-caret-top" size="mini" @click="expandedRowsChange(false)">
                    收起
                </el-button>
                <el-button type="warning" icon="el-icon-d-caret" size="mini" @click="handleSort(1, {})">
                    模块排序
                </el-button>
            </TableToolBar>
            <el-table
                id="tabletree"
                ref="menuTree"
                v-loading="loading"
                :data="tableTreeDdata"
                stripe
                size="mini"
                row-key="id"
                :tree-props="{ children: 'children', hasChildren: 'isleaf' }"
                :expandedRowKeys="expandedRowKeys"
                element-loading-text=" "
                element-loading-custom-class="table-loading-box"
                element-loading-spinner="table-spinner"
                :header-cell-style="{
                    background: themeColor,
                    height: '32px',
                    lineHeight: '32px'
                }"
            >
                <template v-for="item in tableTeeConfig">
                    <el-table-column
                        v-if="item.isSlot == true && item.visible"
                        :prop="item.prop"
                        :align="item.align"
                        :width="item.width"
                        :label="item.label"
                        :key="item.id"
                        :show-overflow-tooltip="item.tooltip"
                    >
                        <template slot-scope="scope">
                            <span v-if="item.slot === 'iconmenu00'">
                                <svg-icon v-if="scope.row.icon" :icon-class="scope.row.icon" />
                                <span v-else>-</span>
                            </span>
                            <span v-if="item.slot === 'type'">
                                <el-tag v-if="scope.row.type === 1" size="small" type="primary">模块</el-tag>
                                <el-tag v-else-if="scope.row.type === 2" size="small" type="success">菜单</el-tag>
                                <el-tag v-else-if="scope.row.type === 3" size="small" type="danger">按钮</el-tag>
                            </span>
                            <span v-if="item.slot === 'isValid'">
                                <el-switch
                                    v-model="scope.row.isValid"
                                    :active-value="1"
                                    :inactive-value="0"
                                    @change="handleEnable(scope.row)"
                                ></el-switch>
                            </span>
                            <template v-if="item.slot === 'createUser'">
                                {{ scope.row.createUser }}
                                <br />
                                {{ scope.row.createTime }}
                            </template>
                            <template v-if="item.slot === 'updateUser'">
                                {{ scope.row.updateUser }}
                                <br />
                                {{ scope.row.updateTime }}
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column
                        v-if="item.isSlot === false && item.visible"
                        :header-align="item.align"
                        :align="item.align"
                        :width="item.width"
                        :label="item.label"
                        :prop="item['prop']"
                        :key="item.label"
                        :show-overflow-tooltip="item.tooltip"
                    >
                        <template slot-scope="scope">
                            {{
                                typeof scope.row[item.prop] === 'number'
                                    ? scope.row[item.prop]
                                    : scope.row[item.prop] || '-'
                            }}
                        </template>
                    </el-table-column>
                </template>
                <el-table-column fixed="right" header-align="center" align="center" width="260" label="操作">
                    <template slot-scope="scope">
                        <el-button icon="el-icon-edit" type="text" size="small" @click="handleEdit('edit', scope.row)">
                            编辑
                        </el-button>
                        <el-button icon="el-icon-delete" type="text" size="small" @click="handleDelete(scope.row)">
                            删除
                        </el-button>

                        <el-button
                            v-if="scope.row.type === 1"
                            icon="el-icon-circle-plus-outline"
                            type="text"
                            size="small"
                            @click="handleAddMenu('menu', scope.row)"
                        >
                            添加菜单
                        </el-button>
                        <el-button
                            v-if="scope.row.type === 1 && scope.row.children && scope.row.children.length > 1"
                            icon="el-icon-d-caret"
                            type="text"
                            size="small"
                            @click="handleSort(2, scope)"
                        >
                            菜单排序
                        </el-button>
                        <el-button
                            v-if="scope.row.type === 2"
                            icon="el-icon-circle-plus-outline"
                            type="text"
                            size="small"
                            @click="handleAddMenu('btn', scope.row)"
                        >
                            添加按钮
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 新增修改界面 -->
        <EditItem
            ref="menuForm"
            v-model="dialogVisible"
            v-if="dialogVisible"
            :dataForm="dataFormDefault"
            :editTag="editTag"
            @getPageList="findTreeList"
            :appManagerData="appManagerList"
            :type.sync="type"
        >
            <el-form-item label="菜单类型" prop="type">
                <el-radio-group
                    v-model="type"
                    :disabled="editTag === 'edit' || editTag === 'menu'"
                    @change="handleRadioref"
                >
                    <el-radio v-for="(type, index) in menuTypeList" :key="index" :label="index + 1">
                        {{ type }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
        </EditItem>
        <MenuSort
            :sortVisible.sync="visibleSortref"
            :columns="columnsSort"
            :menuData="treeCatalogue"
            :type="SortType"
            @getList="findTreeList"
            v-if="visibleSortref"
            :oldSortData="oldSortData"
        ></MenuSort>
    </div>
</template>

<script>
import PopupTreeInput from '@/components/PopupTreeInput'
import FaIconTooltip from '@/components/FaIconTooltip'
import EditItem from './MenuForm'
import { mapState } from 'vuex'
import { confirm, deepClone } from '@/utils/utils'
import { fetchMenuTree, delRes, editRes } from '@/api/system/menu'
import { appManagerPageList } from '@/api/system/application'
import TableToolBar from '@/components/TableToolBar'
import MenuSort from './menuSort.vue'
import utils from '@/utils/utils'

export default {
    name: 'leftmenu',
    components: {
        PopupTreeInput,
        FaIconTooltip,
        EditItem,
        MenuSort,
        TableToolBar
    },
    data() {
        return {
            showSearch: true,
            size: 'small',
            loading: false,
            pageRequest: { pageNum: 1, pageSize: 20 },
            filters: {
                resName: '',
                appId: ''
            },
            // 表格搜索处的字段
            tableHeaderConfig: [
                { title: '菜单名称', code: 'resName', type: 'input' },
                { title: '应用名称', slot: 'appId' }
            ],
            // 表格字段配置
            tableTeeConfig: [
                {
                    label: '菜单名称',
                    prop: 'resourceName',
                    isSlot: false,
                    align: 'left',
                    visible: true,
                    key: 'resourceName',
                    width: '165'
                },
                {
                    label: '类型',
                    slot: 'type',
                    isSlot: true,
                    align: 'center',
                    visible: true,
                    key: 'type'
                },
                {
                    label: '应用名称',
                    prop: 'appName',
                    isSlot: false,
                    align: 'left',
                    visible: true,
                    key: 'appName'
                },
                {
                    label: '状态',
                    slot: 'isValid',
                    isSlot: true,
                    align: 'center',
                    visible: true,
                    key: 'isValid'
                },

                {
                    label: '图标',
                    slot: 'iconmenu00',
                    isSlot: true,
                    align: 'center',
                    visible: true,
                    key: 'iconmenu00'
                },
                {
                    label: '菜单Url',
                    prop: 'url',
                    isSlot: false,
                    tooltip: true,
                    align: 'left',
                    visible: true,
                    key: 'url'
                },
                {
                    label: '授权标识',
                    prop: 'perms',
                    isSlot: false,
                    align: 'left',
                    visible: true,
                    key: 'perms'
                },
                {
                    label: '创建人/创建时间',
                    slot: 'createUser',
                    isSlot: true,
                    width: '150',
                    visible: true,
                    key: 'createUser'
                },
                {
                    label: '更新人/创建时间',
                    slot: 'updateUser',
                    isSlot: true,
                    width: '150',
                    visible: true,
                    key: 'updateUser'
                }
            ],
            tableTreeDdata: [],
            // 是否显示编辑弹窗
            dialogVisible: false,
            // 是否要展示的标识
            expandedRowKeys: true,
            dataForm: {
                description: '',
                icon: '',
                isValid: 1,
                textNum: '',
                parentId: 0,
                perms: '',
                resourceCode: '',
                resourceHierarchy: 1,
                resourceName: '',
                type: 1,
                appId: '',
                url: ''
            },
            dataFormDefault: {},
            editTag: 'add',
            // 应用data
            appManagerList: [],
            //选项卡类型
            type: 1,
            menuTypeList: ['模块', '菜单', '按钮'],
            visibleSortref: false,
            treeCatalogue: [],
            meunSotrtTitle: '',
            columnsSort: [{ label: '菜单名称', prop: 'resourceName' }],
            SortType: 1,
            oldSortData: []
        }
    },
    mounted() {
        this.findTreeList()
        this.appManagerPage()
    },
    activated() {
        console.log('555555')
        this.findTreeList()
        this.appManagerPage()
    },
    computed: {
        ...mapState({
            themeColor: (state) => state.app.themeColor
        })
    },
    methods: {
        // 获取数据
        findTreeList() {
            this.loading = true
            const params = Object.assign({}, this.pageRequest, this.filters)
            fetchMenuTree(params)
                .then((res) => {
                    this.tableTreeDdata = res.data || []
                })
                .finally(() => {
                    this.loading = false
                })
        },
        // 应用列表
        appManagerPage() {
            appManagerPageList({ isValid: 1 }).then((res) => {
                this.appManagerList = res.data
            })
        },
        // 显示编辑或
        handleEdit(tag, row) {
            const { type, appId, parentId } = row
            this.dialogVisible = true
            this.editTag = tag
            this.type = row.type
            this.dataFormDefault = Object.assign({}, row, {
                appId: Number(appId),
                parentId: Number(parentId)
            })
            this.$nextTick(() => {
                this.handleRadioref(type)
                this.$refs.menuForm.handleAppId(appId)
            })
        },
        // 添加菜单 操作处
        handleAddMenu(menu, row) {
            this.appManagerPage()
            const { type, appId, id, resourceCode, resourceHierarchy } = row
            this.dialogVisible = true
            this.editTag = 'menu'
            this.type = type + 1
            this.dataFormDefault = Object.assign(
                {},
                {
                    appId: Number(appId),
                    parentId: Number(id),
                    resourceHierarchy,
                    resourceName: '',
                    url: '',
                    textNum: '',
                    description: '',
                    resourceCode,
                    perms: '',
                    icon: ''
                }
            )
            this.$nextTick(() => {
                this.handleRadioref(2)
                this.$refs.menuForm.handleAppId(appId)
            })
        },
        // 添加按钮
        handleAddBtn(type, row) {},
        // 新增弹框
        handleAdd(tag) {
            this.dialogVisible = true
            this.editTag = tag
            this.type = 1
            this.dataFormDefault = Object.assign({}, this.dataForm)
        },
        // 删除
        handleDelete(row) {
            const { id } = row
            let tip =
                row.children && row.children.length > 0 ? '确认删除该条数据及子级数据吗？' : '确认删除选中记录吗？'
            confirm(tip).then(() => {
                const params = {
                    resourceId: id
                }
                delRes(params).then(() => {
                    this.$message({ message: '删除成功', type: 'success' })
                    this.findTreeList()
                })
            })
        },
        // 启用与禁用
        handleEnable(row) {
            const { isValid } = row
            const tip = isValid === 0 ? '是否要禁用' : '是否要启用'
            const params = Object.assign({}, row, {
                isValid
            })
            confirm(tip)
                .then(() => {
                    editRes(params).then((res) => {
                        console.log(res)
                        this.findTreeList()
                    })
                })
                .catch(() => {
                    row.isValid = isValid === 0 ? 1 : 0
                })
        },
        // 展开与收起的方法
        expandedRowsChange(tag) {
            this.$nextTick(() => {
                this.forArr(this.tableTreeDdata, tag)
            })
        },
        forArr(arr, isExpand) {
            arr.forEach((i) => {
                this.$refs.menuTree.toggleRowExpansion(i, isExpand)
                if (i.children) {
                    this.forArr(i.children, isExpand)
                }
            })
        },
        handleRadioref(type) {
            console.log(type)
            this.$refs.menuForm.handleRadio(type)
        },
        getMenuData(type, row) {},
        // 模块与菜单排序
        handleSort(type, { row }) {
            this.SortType = type
            const thisData = type == 1 ? this.tableTreeDdata : row.children
            const resourceNameParent = row && row.resourceName
            this.meunSotrtTitle = type == 1 ? '模块排序' : `${resourceNameParent}的菜单排序`
            const thisTable = thisData.map((item, index) => {
                const { resourceCode, resourceName, appName, id } = item
                return {
                    resourceCode,
                    resourceName,
                    type,
                    id
                }
            })
            this.treeCatalogue = thisTable
            this.oldSortData = JSON.parse(JSON.stringify(thisTable))

            this.$nextTick(() => {
                this.visibleSortref = true
            })
        }
    }
}
</script>
